package com.example.module_motorcircle.post

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.Router
import com.example.lib_common.base.BaseFragment
import com.example.lib_common.observeWithLifecycle
import com.example.lib_common.state.UIState
import com.example.lib_common.utils.ToastUtils
import com.example.lib_net.model.api.PostItem
import com.example.lib_storage.AuthMMKV
import com.example.module_motorcircle.R
import com.example.module_motorcircle.databinding.FragmentPostListBinding
import com.example.module_motorcircle.dialog.MoreActionDialog
import com.example.module_motorcircle.motor_circle.viewmodel.MotorCircleViewModel
import com.example.module_motorcircle.post.adapter.PostAdapter
import com.example.module_motorcircle.post.viewmodel.PostViewModel
import dagger.hilt.android.AndroidEntryPoint

/**
 * 帖子列表
 */
@AndroidEntryPoint
class PostListFragment : BaseFragment<PostViewModel,FragmentPostListBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.fragment_post_list
    override val mViewModel: PostViewModel by viewModels() //不要共享

    var category:Int? = 0 //分类
    companion object{
        private const val CATEGORY = "category"
        /**
         * 实例化fragment并传值category
         * category：0热门 1帖子 2关注
         */
        fun newInstance(category: Int? = null): PostListFragment {
            val bundle = Bundle()
            if(category != null){
                bundle.putInt(CATEGORY,category)
            }
            val fragment = PostListFragment()
            fragment.arguments = bundle
            return fragment

        }
    }
    private val postAdapter by lazy {
        PostAdapter(
            onItemClick = {postItem,position->
                ARouter.getInstance()
                    .build(Router.MOTOR_CIRCLE_POST_DETAIL_ACTIVITY)
                    .withString("id",postItem.postsId)
                    .navigation()
            },
            onCommentClick = {postItem,position->
                    ARouter.getInstance()
                        .build(Router.MOTOR_CIRCLE_POST_DETAIL_ACTIVITY)
                        .withString("id",postItem.postsId)
                        .navigation()
            },
            onLikeClick = {postItem,position->
                //1.判断用户是否登陆，跳转登陆页面
                if(!AuthMMKV.hasLogin()){
                    ARouter.getInstance().build(Router.MINE_LOGIN_ACTIVITY).navigation()
                    return@PostAdapter
                }
                //2.点赞：点赞前需要判断帖子是否存在
                mViewModel.likeOrCancel(postItem.postsId!!,position)
            },
            onCollectionClick = {postItem,position->
                //1.判断用户是否登陆，跳转登陆页面
                if(!AuthMMKV.hasLogin()){
                    ARouter.getInstance().build(Router.MINE_LOGIN_ACTIVITY).navigation()
                    return@PostAdapter
                }
                //2.收藏和取消
                mViewModel.collectOrCancel(postItem.reverseIfCollect(),postItem.postsId!!,position)
            },
            onFollowClick = {postItem,position->
                //1.判断用户是否登陆，跳转登陆页面
                if(!AuthMMKV.hasLogin()){
                    ARouter.getInstance().build(Router.MINE_LOGIN_ACTIVITY).navigation()
                    return@PostAdapter
                }
                //2.关注和取消关注
                if(postItem.hasFollow()){
                    mViewModel.followCancelMember(postItem.createBy!!,position)
                }else{
                    mViewModel.followMember(postItem.createBy!!,position)
                }
            },
            onMoreClick = {postItem,position->
                //1.判断用户是否登陆，跳转登陆页面
                if(!AuthMMKV.hasLogin()){
                    ARouter.getInstance().build(Router.MINE_LOGIN_ACTIVITY).navigation()
                    return@PostAdapter
                }
                //2:点击更多：弹出对话框-》举报、屏蔽、删除
                clickMoreAction(postItem,position)
            }
        )
    }
    private fun clickMoreAction(postItem: PostItem, position: Int) {
        val ifMy = postItem.ifMy == 1 //是否是自己发布的
        MoreActionDialog(showAction1 = !ifMy, showAction2 = true, action1 = "屏蔽", action2 = if(ifMy) "删除" else "举报",
            onClickAction1 = {
                //屏蔽
                mViewModel.shieldSave(postItem.postsId!!)
            },
            onClickAction2 = {
                //删除或举报
                if(ifMy){//删除
                    mViewModel.deletePost(postItem.postsId!!)
                }else{//举报
                    ARouter.getInstance()
                        .build(Router.MOTOR_CIRCLE_REPORT_ACTIVITY)
                        .withString("id",postItem.postsId)
                        .withString("type","1")
                        .navigation()
                }
            }
        ).show(childFragmentManager,MoreActionDialog.TAG)
    }

    override fun initView() {
        initPostListView()

    }
    private fun initPostListView() {
        mBinding.rv.adapter = postAdapter
        mBinding.rv.layoutManager = LinearLayoutManager(requireActivity())
        mBinding.rv.hasFixedSize() //优化性能 每次不需要layout

    }

    override fun initData() {
        //分类
        category = arguments?.getInt(CATEGORY,0)
        //获得帖子数据
        mViewModel.getPostPage(category = category)

    }

    override fun initListener() {
        //订阅删除事件
        mViewModel.requestDeletePostEvent_.observeWithLifecycle(this){
            if (it){
                ToastUtils.showLong(requireActivity(),"删除成功")
            }else{
                ToastUtils.showLong(requireActivity(),"删除失败")
            }
        }
        //订阅屏蔽事件
        mViewModel.requestShieldEvent_.observeWithLifecycle(this){
            if (it){
                ToastUtils.showLong(requireActivity(),"屏蔽成功")
            }else{
                ToastUtils.showLong(requireActivity(),"屏蔽失败")
            }
        }
        //订阅点赞的事件
        mViewModel.requestLikeEvent_.observeWithLifecycle(this){ it->
            if(it == -1){
                return@observeWithLifecycle
            }
            val post = postAdapter.getPostItem(it)
            if (post.ifLike == 1){
                post.ifLike = 0
                post.likeNumber --
            }else{
                post.ifLike = 1
                post.likeNumber ++
            }
            //局部增量刷新
            postAdapter.notifyItemChanged(it,"updateLike")
        }
        //订阅收藏的事件
        mViewModel.requestCollectEvent_.observeWithLifecycle(this){ it->
            if(it == -1){
                return@observeWithLifecycle
            }
            val post = postAdapter.getPostItem(it)
            if (post.ifCollect == 1){
                post.ifCollect = 0
                post.collectNumber --
            }else{
                post.ifCollect = 1
                post.collectNumber ++
            }
            //局部增量刷新
            postAdapter.notifyItemChanged(it,"updateCollect")
        }
        //订阅关注的事件
        mViewModel.requestFollowEvent_.observeWithLifecycle(this){ it->
            if(it == -1){
                return@observeWithLifecycle
            }
            val post = postAdapter.getPostItem(it)
            if (post.hasFollow()){
                post.onCancelFollow()
            }else{
                post.onFollow()
            }
            //局部增量刷新
            postAdapter.notifyItemChanged(it,"updateFocus")
        }
        //订阅数据
        mViewModel.postState_.observeWithLifecycle(this){
            when(it){
                is UIState.Loading -> {
                    setLoadingViewVisible(true,"请求数据中。。。。")
                }
                is UIState.Success -> {
                    setLoadingViewVisible(false)
                    postAdapter.setData(mViewModel.postList)

                }
                is UIState.Error -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(requireActivity(),"数据请求失败")
                }
                is UIState.Empty -> {
                    setLoadingViewVisible(false)
                    ToastUtils.showLong(requireActivity(),"空数据")
                }
                else -> {

                }
            }
        }
    }

}